package controllers

import (
	"encoding/json"
	"fmt"
	"time"

	"gitee.com/lzqysoft/ga_wz_backend/libs"
	"gitee.com/lzqysoft/ga_wz_backend/libs/encrypt"
	"gitee.com/lzqysoft/ga_wz_backend/models"
	"github.com/astaxie/beego"
)

type TodoController struct {
	CommonController
}

// URLMapping ...
func (c *TodoController) URLMapping() {
	c.Mapping("GetDaiShouJian", c.GetDaiShouJian)
	c.Mapping("GetJianYanZhong", c.GetJianYanZhong)
	c.Mapping("GetDaiQuJian", c.GetDaiQuJian)
	c.Mapping("GetDaiSongJian", c.GetDaiSongJian)
	c.Mapping("GetYiQuJian", c.GetYiQuJian)
	c.Mapping("UpdateTodoStatus", c.UpdateTodoStatus)
	c.Mapping("GetListByBusy", c.GetListByBusy)
	c.Mapping("AddSuggest", c.AddSuggest)
	c.Mapping("GetUserTodoList", c.GetUserTodoList)
	c.Mapping("GetJianDingZhong", c.GetJianDingZhong)
	c.Mapping("StopJianYan", c.StopJianYan)
}

// GetDaiShouJian ...
// @Title GetDaiShouJian
// @Description GetDaiShouJian
// @Param	body		body 	[]models.TodoManager	true		"body for TodoManager content"
// @Success 201 {int} models.SfSfyy
// @Failure 403 body is empty
// @router /GetDaiShouJian [get]
func (c *TodoController) GetDaiShouJian() {
	user := c.User
	res, err := models.GetDaiShouJian(user)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrNoData)
	}
	c.RetSuccess(res)
}

// GetJianYanZhong ...
// @Title GetJianYanZhong
// @Description GetDaiShouJian
// @Param	body		body 	[]models.TodoManager	true		"body for TodoManager content"
// @Success 201 {int} models.SfSfyy
// @Failure 403 body is empty
// @router /GetJianYanZhong [get]
func (c *TodoController) GetJianYanZhong() {
	user := c.User
	res, err := models.GetJianYanZhong(user)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrNoData)
	}
	c.RetSuccess(res)
}

// GetJianDingZhong ...
// @Title GetJianDingZhong
// @Description GetJianDingZhong
// @Param	body		body 	[]models.TodoManager	true		"body for TodoManager content"
// @Success 201 {int} models.SfSfyy
// @Failure 403 body is empty
// @router /GetJianDingZhong [get]
func (c *TodoController) GetJianDingZhong() {
	user := c.User
	res, err := models.GetJianDingZhong(user)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrNoData)
	}
	c.RetSuccess(res)
}

// GetDaiQuJian ...
// @Title GetDaiQuJian
// @Description GetDaiQuJian
// @Param	body		body 	[]models.TodoManager	true		"body for TodoManager content"
// @Success 201 {int} models.SfSfyy
// @Failure 403 body is empty
// @router /GetDaiQuJian [get]
func (c *TodoController) GetDaiQuJian() {
	user := c.User
	res, err := models.GetDaiQuJian(user)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrNoData)
	}
	c.RetSuccess(res)
}

// GetYiQuJian ...
// @Title GetYiQuJian
// @Description GetYiQuJian
// @Param	body		body 	[]models.TodoManager	true		"body for TodoManager content"
// @Success 201 {int} models.SfSfyy
// @Failure 403 body is empty
// @router /GetYiQuJian [get]
func (c *TodoController) GetYiQuJian() {
	user := c.User
	res, err := models.GetYiQuJian(user)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrNoData)
	}
	c.RetSuccess(res)
}

// GetDaiSongJian ...
// @Title GetDaiSongJian
// @Description GetDaiQuJian
// @Param	body		body 	[]models.TodoManager	true		"body for TodoManager content"
// @Success 201 {int} models.GetDaiSongJian
// @Failure 403 body is empty
// @router /GetDaiSongJian [get]
func (c *TodoController) GetDaiSongJian() {
	user := c.User
	res, err := models.GetDaiSongJian(user)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrNoData)
	}
	c.RetSuccess(res)
}

// UpdateTodoStatus ...
// @Title UpdateTodoStatus
// @Description UpdateTodoStatus
// @Success 201 {int} models.TodoManager
// @Failure 403 body is empty
// @router /UpdateTodoStatus [post]
func (c *TodoController) UpdateTodoStatus() {
	user := c.User
	tdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		beego.Error(err)
		c.RetError(ErrToken)
	}
	fdata, ok := tdata.(map[string]interface{})
	if !ok {
		beego.Debug(ErrInputData)
		c.RetError(ErrInputData)
	}
	todoid, ok := fdata["Id"]
	//item.CinPhone = ""
	//item.CinTime = time.Now()
	//item.CinUser = ""

	if !ok {
		beego.Debug(ErrInputData)
		c.RetError(ErrInputData)
	}
	phone, ok := fdata["Phone"]
	if !ok {
		beego.Debug(ErrInputData)
		c.RetError(ErrInputData)
	}
	remark, ok := fdata["Remark"]
	if !ok {
		beego.Debug(ErrInputData)
		c.RetError(ErrInputData)
	}
	UserAbbr, ok := fdata["User"]
	if !ok {
		beego.Debug(ErrInputData)
		c.RetError(ErrInputData)
	}
	// 更新现有待办事项状态
	todo, err := models.GetSfTodoManagerById(todoid.(string))
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	if todo.Finish != 1 {
		todo.Utime = time.Now()
		todo.Updater = user.Abbr
		todo.Finish = 1
		todo.Finisher = fmt.Sprint(UserAbbr)
		if err = models.UpdateSfTodoManagerById(todo); err != nil {
			beego.Debug(err)
			c.RetError(ErrInputData)
		}
		// 新建代办事项
		doing := models.GenerateSfTodoManager()
		doing.BusyId = todo.BusyId
		doing.BusyName = todo.BusyName
		doing.Creater = user.Abbr
		doing.Type = todo.Type + 1
		doing.Name = libs.GetMTodoTitleByType(doing.Type)
		doing.JyType = todo.JyType
		doing.Title = libs.GetMTodoTitleByType(doing.Type)
		doing.RoleId = todo.RoleId
		doing.Content = todo.Content
		doing.Remark = fmt.Sprint(remark)
		add := true
		if sfCase, err := models.GetSfCaseById(todo.BusyId); err == nil {
			sfCase.Status++
			if sfCase.Status == 4 {
				// 确认取件
				sfCase.Start = 1
				sfCase.StartTime = time.Now()
				// 如果 是补充，那么就copy一条item插入,并解锁原case, 不新建代办，
				if sfCase.IsAdditional == 1 && sfCase.AdditionalId != "" {
					items, _ := models.GetSfCaseItemsBySfCase(sfCase.Id)
					item := items[0]
					sourceSfCase, _ := models.GetSfCaseById(sfCase.AdditionalId)
					m := *&item
					m.Id = encrypt.GetGuid()
					m.SfCaseId = sourceSfCase.Id
					models.AddSfCaseItem(&m)
					sourceSfCase.Lock = 0
					models.UpdateSfCaseById(sourceSfCase)
					add = false
				}
				userTodo := models.GenerateSfTodouser()
				userTodo.UserId = sfCase.Uid
				userTodo.Title = sfCase.Title
				userTodo.Name = "状态变更"
				userTodo.Content = sfCase.Title + "的状态已变更为检验，操作人是" + user.Abbr + ", 联系电话为：" + user.Phone
				models.AddSfTodoUser(userTodo)
			}
			if sfCase.Status == 5 {
				// 检验
				// userTodo := models.GenerateSfTodouser()
				// userTodo.UserId = sfCase.Uid
				// userTodo.Title = sfCase.Title
				// userTodo.Name = "待取件"
				// userTodo.Content = sfCase.Title + "有一个" + libs.GetUTodoTitleByType(1) + "事项"
				// models.AddSfTodoUser(userTodo)
				userTodo := models.GenerateSfTodouser()
				userTodo.UserId = sfCase.Uid
				userTodo.Title = sfCase.Title
				userTodo.Name = "状态变更"
				userTodo.Content = sfCase.Title + "的状态已变更为鉴定，操作人是" + user.Abbr + ", 联系电话为：" + user.Phone
				models.AddSfTodoUser(userTodo)
			}
			if sfCase.Status == 6 {
				// 鉴定完成，待取件
				sfCase.Finish = 1
				sfCase.FinishTime = time.Now()
				//beego.Debug("执行了吱吱吱吱这里吗？")
				// 添加待取件信息
				userTodo := models.GenerateSfTodouser()
				userTodo.UserId = sfCase.Uid
				userTodo.Title = sfCase.Title
				userTodo.Name = "待取件"
				userTodo.Content = sfCase.Title + "有一个" + libs.GetUTodoTitleByType(1) + "事项，操作人是" + user.Abbr + ", 联系电话为：" + user.Phone

				models.AddSfTodoUser(userTodo)
			}
			if sfCase.Status == 7 {
				// 已取件
				//sfCase.Finish = 1
				//sfCase.FinishTime = time.Now()

				userTodo := models.GenerateSfTodouser()
				userTodo.UserId = sfCase.Uid
				userTodo.Title = sfCase.Title
				userTodo.Name = "完成"
				userTodo.Content = sfCase.Title + "的状态已变更为完成，操作人是" + user.Abbr + ", 联系电话为：" + user.Phone

				models.AddSfTodoUser(userTodo)

				// 生成评价信息
				m := models.NewSfRate()
				m.Name = sfCase.Title
				m.BusyId = todo.BusyId
				m.BusyName = todo.BusyName
				m.UserId = sfCase.Cid
				m.TodoId = doing.Id
				models.AddSfRate(m)
			}
			//models.UpdateSfCaseById(sfCase)
			if items, err := models.GetSfCaseItemsBySfCase(todo.BusyId); err == nil {
				item := items[0]
				item.Cin = 1
				item.CinUser = UserAbbr.(string)
				item.CinTime = time.Now()
				item.CinPhone = phone.(string)
				models.UpdateSfCaseItemById(&item)
			}
			if err := models.UpdateSfCaseById(sfCase); err != nil {
				beego.Debug(err)
			}
		} else {
			beego.Debug(err)
		}

		if add {
			if _, err = models.AddSfTodoManager(doing); err != nil {
				beego.Debug(err)
				c.RetError(ErrInputData)
			}
		}
	}

	// 更新预约状态

	c.RetSuccess(nil)

}

type stopBody struct {
	Id     string
	Type   int
	Remark string
}

// StopJianYan ...
// @Title StopJianYan
// @Description StopJianYan
// @Success 201 {int} models.TodoManager
// @Failure 403 body is empty
// @router /StopJianYan [post]
func (c *TodoController) StopJianYan() {
	user := c.User
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		beego.Error(err)
		c.RetError(ErrToken)
	}

	var params stopBody
	if err = json.Unmarshal(tdata, &params); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}

	// 更新现有待办事项状态
	todo, err := models.GetSfTodoManagerById(params.Id)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	if todo.Finish != 1 {
		todo.Utime = time.Now()
		todo.Updater = user.Abbr
		todo.Finish = 1
		todo.Remark = params.Remark
		todo.Finisher = user.Abbr
		if err = models.UpdateSfTodoManagerById(todo); err != nil {
			beego.Debug(err)
			c.RetError(ErrInputData)
		}
		// 新建代办事项
		doing := models.GenerateSfTodoManager()
		doing.BusyId = todo.BusyId
		doing.BusyName = todo.BusyName
		doing.Creater = user.Abbr
		doing.Type = 4
		doing.Remark = libs.GetTopStr(params.Type)
		doing.Name = libs.GetMTodoTitleByType(doing.Type)
		doing.JyType = todo.JyType
		doing.Title = libs.GetMTodoTitleByType(doing.Type)
		doing.RoleId = todo.RoleId
		doing.Content = todo.Content
		add := true
		if sfCase, err := models.GetSfCaseById(todo.BusyId); err == nil {
			sfCase.Status = 7

			if sfCase.Status == 7 {
				// 已取件
				//			//sfCase.Finish = 1
				//			//sfCase.FinishTime = time.Now()

				// 用户通知
				userTodo := models.GenerateSfTodouser()
				userTodo.UserId = sfCase.Uid
				userTodo.Title = sfCase.Title
				userTodo.Name = "通知"
				userTodo.Content = sfCase.Title + "已" + libs.GetTopStr(params.Type) + ", 请再次预约！"
				models.AddSfTodoUser(userTodo)
			}
			//models.UpdateSfCaseById(sfCase)
			//if items, err := models.GetSfCaseItemsBySfCase(todo.BusyId); err == nil {
			//	item := items[0]
			//	item.Cin = 1
			//	item.CinUser = UserAbbr.(string)
			//	item.CinTime = time.Now()
			//	item.CinPhone = phone.(string)
			//	models.UpdateSfCaseItemById(&item)
			//}

			// 判断是否生成评价 ， 0，2 即不予受理，终止检验评价
			if params.Type == 2 || params.Type == 0 {
				m := models.NewSfRate()
				m.Name = sfCase.Title
				m.BusyId = todo.BusyId
				m.BusyName = todo.BusyName
				m.UserId = sfCase.Cid
				m.TodoId = doing.Id
				models.AddSfRate(m)
			}

			if err := models.UpdateSfCaseById(sfCase); err != nil {
				beego.Debug(err)
			}
		} else {
			beego.Debug(err)
		}
		if add {
			if _, err = models.AddSfTodoManager(doing); err != nil {
				beego.Debug(err)
				c.RetError(ErrInputData)
			}
		}
	}

	c.RetSuccess(nil)
}

// GetListByBusy ...
// @Title GetListByBusy
// @Description GetListByBusy
// @Param	body		body 	models.SfTodoManager
// @Success 201 {int} models.SfTodoManager
// @Failure 403 id is empty
// @router /GetListByBusy/:id [get]
func (c *TodoController) GetListByBusy() {
	busyId := c.Ctx.Input.Param(":id")
	if res, err := models.GetSfTodoManagerByBusy(busyId); err == nil {
		c.RetSuccess(res)
	} else {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
}

// AddSuggest ...
// @Title AddSuggest
// @Description AddSuggest
// @Success 201 {int}  0
// @Failure 403 body is empty
// @router /AddSuggest [post]
func (c *TodoController) AddSuggest() {
	tdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var suggest models.Suggest
	if err = json.Unmarshal(tdata, &suggest); err != nil {
		beego.Debug(err)
		c.RetError(ErrInputData)
	}
	models.AddSuggest(suggest.Score, suggest.Suggest)
	c.RetSuccess(nil)
}

// GetUserTodoList ...
// @Title GetUserTodoList
// @Description GetUserTodoList
// @Success 201 {int} models.SfTodoUser
// @Failure 403 body is empty
// @router /GetUserTodoList [get]
func (c *TodoController) GetUserTodoList() {
	user := c.User
	res, err := models.GetSfTotoListByUser(user.Id)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrNoData)
	}
	c.RetSuccess(res)
}
